package com.jzsm.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.jzsm.common.exception.BusinessException;

import java.util.Arrays;
import java.util.HashMap;

public class JwtUtils {
    public final static byte[] TOKEN_KEY = "12345678".getBytes();
    public final static int EXPIRE_MINUTE = 3600;

    /**
     * 校验白名单
     *
     * @param whitePaths
     * @param inputPath
     * @return
     */
    public final static boolean checkWhitePath(String whitePaths, String inputPath) {
        String[] split = whitePaths.split("\\,");
        if (
                split != null &&
                        split.length > 0
        ) {
            long count = Arrays.stream(split).filter(
                    path -> {
                        String trimStr = path.trim();
                        if (StringUtils.isNotBlank(trimStr)) {
                            String regexp = trimStr.replace("/**", "/(.)*$");
                            return inputPath.matches(regexp);
                        }
                        return false;
                    }
            ).count();
            return count > 0;
        }
        return false;
    }

    /**
     * 校验 JWT 是否过期
     *
     * @return
     */
    public final static boolean verifyEXpired(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        boolean verify = jwt.setKey(TOKEN_KEY).verify();
        System.out.println("------校验token key：" + verify);
        boolean verifyTime = jwt.validate(0);
        return verifyTime;
    }

    public final static JSONObject getPayloadMap(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        JSONObject payloads = jwt.getPayloads();
        return payloads;
    }

    public final static String createToken(HashMap<String, Object> payloadMap) {
        HashMap<String, Object> data = new HashMap<>();
        DateTime now = DateTime.now();
        DateTime expiresAt = now.offsetNew(DateField.YEAR, JwtUtils.EXPIRE_MINUTE);
        BeanUtil.copyProperties(payloadMap, data);

        // 签发时间
        data.put(JWTPayload.ISSUED_AT, now);

        // 过期时间
        data.put(JWT.EXPIRES_AT, expiresAt);

        // 生效时间
        data.put(JWTPayload.NOT_BEFORE, now);

        String token = JWT.create()
                .addPayloads(data)
                .setKey(TOKEN_KEY).sign();
        return token;
    }

    public static String exchangeToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        JSONObject payloads = jwt.getPayloads();

        HashMap<String, Object> map = new HashMap<>();
        String[] removeKeys = {"nbf", "exp", "iat"};

        payloads.forEach((key, value) -> {
            map.put(key, value);
        });
        Arrays.stream(removeKeys).forEach(key -> map.remove(key));
        boolean verify = jwt.setKey(TOKEN_KEY).verify();
        if (verify) {
            return JwtUtils.createToken(map);
        } else {
            throw new BusinessException("不允许替换token！");
        }
    }
}
